package com.kk.xhr.admin.controller;

import com.kk.xhr.admin.util.FileUtil;
import com.kk.xhr.web.vo.ApiResult;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;

/**
 * 文件管理器
 *
 * @author kkmystery
 * @version 1.0 2021/3/25
 * @since 1.0.0
 */
@RestController
@RequiredArgsConstructor
@Api(value = "文件管理", tags = "文件管理")
@RequestMapping("/file")
public class FileController {
    private final Executor fileControllerExecutor;

    @PostMapping("/upload")
    public CompletionStage<ApiResult<String>> upload(MultipartFile file, HttpServletRequest request) {
        return CompletableFuture.supplyAsync(() ->
            ApiResult.success(FileUtil.uploadFile(file, request)), fileControllerExecutor);
    }

    @GetMapping("/download")
    public Object download(String fileName, HttpServletResponse response) {
        return CompletableFuture.supplyAsync(() ->  {
            FileUtil.download(fileName, response);
            return null;
        }, fileControllerExecutor);
    }
}
